<template>
  <div>
    <el-select class="width100" v-model="selectValue" autocomplete :disabled="disabled" :style="customStyle"
               :placeholder="tips?tips:placeholder" :filterable="filterable" clearable @change="changHandl">
      <el-option
        v-for="item in options"
        :key="item.key"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'el-dict',
  componentName: 'ElDict',
  data() {
    return {
      options: [],
      selectValue: null
    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    customStyle: {
      type: Object,
      default() {
        return {}
      }
    },
    // 枚举名
    placeholder: {
      type: String,
      defult: '请选择'
    },
    // 枚举名
    enumName: {
      type: String
    },
    // 导入的url地址
    code: {
      type: String
    },
    // 接受外部v-model传入的值，必须使用value
    value: {
      type: [String, Number]
    },
    tips: {
      type: String
    },
    filterable: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 判断下拉框的值是否有改变
    selectValue(val, oldVal) {
      if (val === '') {
        this.selectValue = null
      }
      if (val !== oldVal) {
        this.$emit('input', this.selectValue)
      }
    },
    value(val) {
      if (typeof val === 'number') {
        this.selectValue = val.toString()
      } else {
        this.selectValue = val
      }
    }
  },
  mounted() {
    if (this.enumName) {
      // 远程请求回来的数据
      this.$http({
        url: '/sys/dict/list-enum',
        params: {
          enumCode: this.enumName
        }
      }).then((response) => {
        if (response.data.type) {
          this.placeholder = this.tips ? this.tips : this.placeholder
        }
        for (let i = 0; i < response.data.list.length; i++) {
          this.options[i] = {}
          this.options[i].label = response.data.list[i]['name']
          this.options[i].value = response.data.list[i]['value']
          this.options[i].key = i
        }
        this.$forceUpdate()
      })
    } else {
      // 远程请求回来的数据
      this.$http('/sys/dict/queryByCode?code=' + this.code)
        .then((response) => {
          if (response.data.type) {
            this.placeholder = this.tips ? this.tips : this.placeholder
          }
          for (let i = 0; i < response.data.list.length; i++) {
            this.options[i] = {}
            this.options[i].label = response.data.list[i]['name']
            this.options[i].value = response.data.list[i]['value']
            this.options[i].key = i
          }
          this.$forceUpdate()
        })
    }
  },
  methods: {
    changHandl(val) {
      this.$emit('change', val)
    }
  }
}
</script>
